	// read config file
	global.config = require('./configs/config');
	// add setting values
	function adjustDbSettings(config)
	{

		if(! ('multipleStatements' in config))
			config['multipleStatements'] = true;	// for stored procedure output param

		if(! ('connectionLimit' in config))
			config['connectionLimit'] = 2;

		if(! ('waitForConnections' in config))
			config['waitForConnections'] = true;

		if(! ('autoReconnect' in config))
			config['autoReconnect'] = true;

		if(! ('useConnectionPooling' in config))
			config['useConnectionPooling'] = true;

		if(! ('reconnectDelay' in config))
			config['reconnectDelay'] = 500;

		if(! ('maxReconnectAttempts' in config))
			config['maxReconnectAttempts'] = 25;

		if(! ('keepAlive' in config))
			config['keepAlive'] = true;

		if(! ('keepAliveInterval' in config))
			config['keepAliveInterval'] = 30000;

	}

	adjustDbSettings(global.config.database.master);
	var MySQLConnectionManager = require('mysql-connection-manager'); // for mysql db HA , pool
	global.master_db = new MySQLConnectionManager(global.config.database.master);

	/*******************************************************************************************/

	var lastId=null;
	var pushKeyCount=300;
	var totalCount = 0;

	var isStart = false;
	var isEnd = false;

	var workHour = (new Date()).getHours();
	var passedDays = 4;

	var filePath = '/home/ec2-user/nodejs/log/noArticle_';

	if(passedDays < 10) filePath += '0';
	filePath += passedDays+'day_';
	
	if(workHour < 10) filePath += '0';
	filePath += workHour+'.log';

	//var filePath = 'd:\\\\tmp\\log\\noArticle_'+passedDays+'day_'+workHour+'.log'; // test 

	function setWorkFinished(callback)
	{

		var d = new Date();
		var timestring = d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

		var msg = "PUSH FINISHED accum count : " + totalCount;

		// 종료시에는 기존파일에 더함.
		require('fs').appendFile(filePath, '['+timestring+'] ' + msg +'\r\n', function(err) {
				if(err) throw err;

				callback();
		});
	}

	function appendFile(str)
	{
		var d = new Date();
		var timestring = d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

		require('fs').appendFile(filePath, '['+timestring+'] ' + str+'\r\n', function(err) {
				if(err) throw err;
		});
	}


	// connection 은 한번만 - 계속 재활용해야 함 (session base temp table)
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) throw err;

		var async = require('async');
		async.whilst(
			function () { return !isEnd;},
			function (callback) {

				var input_param = [workHour , passedDays , lastId , pushKeyCount];
				var sql = "call manage_getPushKeyWithNoArticle(?,?,?,?,@result); SELECT @result as result;";

				var query = connection.query(sql, input_param , function (err, rows) 
				{
					if(err) throw err;

					// 이미 그 시간대 배치가 실행중
					if(rows.length < 3 && rows[1][0].result == 0)
					{
						appendFile('ERROR : previous job is not yet finished ');
						console.log('error : previous job is not yet finished ');
						
						isEnd=true;
						setWorkFinished(callback);
					}
					else
					{
						var list  = rows[0];

						if(list.length == 0)
						{

							isEnd = true;

							setWorkFinished(callback);

						}
						else
						{

							// 시작할 때 - 대상항목이 있을 경우
							if(!isStart)
							{
								isStart = true;

								var d = new Date();
								var timestring = d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

								var str = '['+timestring+'] workHour [' + workHour + '] PUSH STARTED\r\n';

								// 시작할 때는 생성
								require('fs').writeFile(filePath, str , function(err) {
										if(err) throw err;

								});

							}

							lastId = list[list.length-1].id; 

							appendFile('last id : ' + lastId + ', count : ' + list.length);
							console.log('last id : ' + lastId + ', count : ' + list.length);
							
							// 푸시 메시지 만든다.

							var pushList = [];

							//////////// test ////////////////
							/*
							list[0].token='535c8c441490dcf38de04c2cddbfe2d08e62d0df5d161c390bd5ac45696d4b20';
							list[0].appId = 'ios.alivemovie.com';
							list[0].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/90683d85-313b-3e24-a09b-3212a5f9241a';

							list[1].token='0b1c5988acb3ab5e134deac45e8392dd0b7d0bac394aa88867308ec463f3b12f';
							list[1].appId = 'ios.alivemovie.com';
							list[1].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/48548bec-1a43-354e-8781-bfb6eef72510';

							list[2].token='a188303569ff770cbb8bcc2216eff7c129ee7932e06b0996e27ab974d67dfd76';
							list[2].appId = 'ios.alivemovie.com';
							list[2].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/5fa2d220-91d3-3e82-88c5-ecad84d03293';

							list[3].token='dueUsYnzI4A:APA91bHQ40YEzfoVG4ys41RdDZ0fYVcosvm2uwKidLlIrcNWbIkKktsofHYwcQIHGswwd_5zKxqcVmBruT_9z_bwUwVhwhoTQBg4ECJcJTZ19_UAkOa8feZDTm9FFoZn47Ap0tl13wGu';
							list[3].appId = 'android.alivemovie.com';
							list[3].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/GCM/AliveService-Android/5eb8d751-7fb3-3676-b971-399eff7dc935';

							list[4].token='3d066e9cd258db8aff582bd105775545ff3673e6374adb6be68751a13256cbd0';
							list[4].appId = 'ios.alivemovie.com';
							list[4].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/8e9a6b96-70c8-3744-85d8-fdb2fc296c8d';

							list[5].token='535c8c441490dcf38de04c2cddbfe2d08e62d0df5d161c390bd5ac45696d4b20';
							list[5].appId = 'ios.alivemovie.com';
							list[5].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/90683d85-313b-3e24-a09b-3212a5f9241a';

							list[6].token='0b1c5988acb3ab5e134deac45e8392dd0b7d0bac394aa88867308ec463f3b12f';
							list[6].appId = 'ios.alivemovie.com';
							list[6].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/48548bec-1a43-354e-8781-bfb6eef72510';

							list[7].token='a188303569ff770cbb8bcc2216eff7c129ee7932e06b0996e27ab974d67dfd76';
							list[7].appId = 'ios.alivemovie.com';
							list[7].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/5fa2d220-91d3-3e82-88c5-ecad84d03293';

							list[8].token='dueUsYnzI4A:APA91bHQ40YEzfoVG4ys41RdDZ0fYVcosvm2uwKidLlIrcNWbIkKktsofHYwcQIHGswwd_5zKxqcVmBruT_9z_bwUwVhwhoTQBg4ECJcJTZ19_UAkOa8feZDTm9FFoZn47Ap0tl13wGu';
							list[8].appId = 'android.alivemovie.com';
							list[8].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/GCM/AliveService-Android/5eb8d751-7fb3-3676-b971-399eff7dc935';

							list[9].token='3d066e9cd258db8aff582bd105775545ff3673e6374adb6be68751a13256cbd0';
							list[9].appId = 'ios.alivemovie.com';
							list[9].endpointArn='arn:aws:sns:us-west-2:085307523710:endpoint/APNS/AliveService-iOS/8e9a6b96-70c8-3744-85d8-fdb2fc296c8d';
							*/
							/////////////////////////////////


							for(var i = 0 ; i < list.length ; i ++)
							{
								///// test ////
								/*
								if(i>0)
									break;
								*/
								///////////////

								var pushInfo = {};

								// token , endpointArn , appId , message)
								pushInfo = list[i];
							

								pushInfo.sound = true; //사운드 


								pushList[i] = pushInfo;



								appendFile('['+totalCount+'] ['+i+'] ' + list[i].countryCode +',' + list[i].appId + ',' + list[i].endpointArn);
								//console.log('['+totalCount+'] ['+i+'] ' + JSON.stringify(list[i]));

								// total 카운트 하나 늘림.
								totalCount ++;

							}


							// 푸시 날린다.
							var pushFunction = require('./routes/v0.7/functions/cbPush');
							//var pushFunction = require('../../servers/manage/routes/v0.7/functions/cbPush');  //test 
							pushFunction(pushList , callback);


						} // list.length > 0

					}//if(rows.length < 3 && rows[1][0].result == 0) else

				}); // query


			},
			function (err) {

				connection.release(); // 다썼으니 반납

				console.log("accum count : " + totalCount);
				process.exit(1);
			}

		); // whilst 

	}); // connection 





/*
1. 실제로 없는 애들인지 확인
2. 날리는거 테스트 
*/